package kayao.client.input;

import com.chopsticks3d.math.FastMath;

import kayao.client.data.SharedMemory;
import kayao.client.scene.objects.CarNode;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.FloatMath;

/**
 * Handles all input from the phone accelerometer.
 */
public class AccelerometerInput implements SensorEventListener {
	private static final int ACCELEROMETER_DELAY = SensorManager.SENSOR_DELAY_GAME;
	private SensorManager sensorManager;

	// Used for calculations
	private float mAngle;
	private float mX;
	private float mZ;

	/**
	 * Constructor for initializing the listening.
	 * @context the context of the activity.
	 */
	public AccelerometerInput(Context context) {
		sensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
	}

	/**
	 * Start listening to the accelerometer.
	 */
	public void start() {
		// Activate accelerometer listening
		sensorManager.registerListener(this,
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				ACCELEROMETER_DELAY);
	}
	
	public void terminate() {
        try {
            if (sensorManager != null && this != null) {
                sensorManager.unregisterListener(this);
            }
        } catch (Exception e) {}
//		sensorManager.unregisterListener(this);
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// Get values in the phone's x, y and z axes.
		float[] values = event.values;
		int sensor = event.sensor.getType();
		if (sensor == Sensor.TYPE_ACCELEROMETER) {
			// Handle accelerometer input
			CarNode avatar = SharedMemory.getInstance().getAvatar();

			// Temporary for moving around
			synchronized(avatar) {
				avatar.deltaRotation = values[1] * 20;
				mAngle = (avatar.getRotationY() - 90) * FastMath.DEG_TO_RAD;
				mX = FloatMath.sin((FastMath.PI/2 + mAngle));
				mZ = FloatMath.cos((FastMath.PI/2 + mAngle));
				
				if (-values[0] > -3) {
					values[0] = 3;
				}
				float speed = (-values[0] + 6.0f) * 3;
				
				if (Math.abs(values[1]) / 2 >= 1) {
					speed /= Math.abs(values[1]) / 2;
				}
				
				avatar.setVelocityX(mX * speed);
				avatar.setVelocityZ(mZ * speed);
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

}
